<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { initHls, hls } from '../utils/hlsManager'

const props = defineProps<{
  src: string
  currentTime?: number
}>()

const emit = defineEmits<{
  timeupdate: [time: number]
}>()

const videoRef = ref<HTMLVideoElement | null>(null)
const currentSegment = ref('')
const fullSegmentUrl = ref('')

const initializePlayer = () => {
  if (props.src && videoRef.value) {
    initHls(
      props.src,
      videoRef.value,
      (segment: string) => currentSegment.value = segment,
      (url: string) => fullSegmentUrl.value = url,
      props.currentTime
    )
  }
}

watch(() => props.src, (newUrl) => {
  if (newUrl && videoRef.value) {
    initHls(
      newUrl,
      videoRef.value,
      (segment: string) => currentSegment.value = segment,
      (url: string) => fullSegmentUrl.value = url,
      props.currentTime
    )
  }
})

watch(() => props.currentTime, (newTime) => {
  if (videoRef.value && newTime !== undefined) {
    videoRef.value.currentTime = newTime
  }
})

onMounted(() => {
  initializePlayer()
})

onBeforeUnmount(() => {
  hls?.destroy()
})

const handleTimeUpdate = (event: Event) => {
  const video = event.target as HTMLVideoElement
  emit('timeupdate', video.currentTime)
}
</script>

<template>
  <div class="flex flex-col gap-2 w-full">
    <video
      ref="videoRef"
      class="w-full max-w-3xl h-auto bg-black rounded"
      controls
      @timeupdate="handleTimeUpdate"
    ></video>
    <div class="flex flex-col gap-1 text-sm text-gray-600">
      <div v-if="fullSegmentUrl" class="break-all">
        <span class="font-medium">当前片段 URL:</span> {{ fullSegmentUrl }}
      </div>
      <div v-if="currentSegment" class="break-all">
        <span class="font-medium">片段名称:</span> {{ currentSegment }}
      </div>
    </div>
  </div>
</template>
